import tempfile
import os
from lxml.etree import _Element as Element
from lxml import etree


def adb_shell(cmd):
    result = os.popen(cmd).read()
    return result


def get_clear_xmln(xml_text):
    s = xml_text.find("xmln")
    e = xml_text.find("revision")
    return xml_text[0:s] + xml_text[e:]


def ename(e: Element):
    """
    <name>SS</name>
    OR
    <name>
        <name>EE</name>
        <name>....</name>
    </name>
    """
    if e.xpath("./name"):
        return element_to_text(e.xpath("./name")[0])
    else:
        return element_to_text(e)


def element_like_star(element1: Element, element2: Element) -> bool:
    if element1.tag != element2.tag:
        return False
    if element1.get("ignore") == "yes":
        return True
    if len(element1.getchildren()) != len(element2.getchildren()):
        return False
    else:
        if len(element1.getchildren()) == 0 and len(element2.getchildren()) == 0:
            return element1.tag == element2.tag
        else:
            r = 0
            for index in range(0, len(element1.getchildren())):
                equal = element_like_star(element1.getchildren()[index], element2.getchildren()[index])
                r += int(equal)
            return r == len(element1.getchildren())


def src2xml(method_string: str, clear_xmln=True) -> str:
    tmp = tempfile.NamedTemporaryFile(mode='w+', suffix='.java', delete=False, encoding="utf-8")
    tmp.write(method_string)
    tmp.close()
    cmd = "srcml {0}".format(tmp.name)
    ret = adb_shell(cmd)
    os.remove(tmp.name)
    if clear_xmln:
        return get_clear_xmln(ret)
    return ret


def element_to_text(e: Element, encoding='utf-8'):
    if e is not None:
        return etree.tostring(e, encoding=encoding, method='text', pretty_print=True).decode(encoding).strip()
    else:
        return ""


def element_to_xml_text(e: Element, encoding='utf-8'):
    if e is not None:
        return etree.tostring(e, encoding=encoding, pretty_print=True).decode(encoding)
    else:
        return ""


def root_from_file(file: str):
    with open(file, "r", encoding='utf-8') as xml:
        bi_xml = xml.read()
        bi_xml = get_clear_xmln(bi_xml)
        root = etree.fromstring(bi_xml.encode('utf-8'))
        return root


if __name__ == '__main__':
    print(src2xml(open('../testcase/code.java', encoding="utf-8").read()))
